import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Tabs,
  Table,
  Radio,
} from 'antd';
import GeneralTableComponent from 'components/GeneralTableComponent';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
const {  RangePicker} = DatePicker;
import styles from './TableList.less';
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
const { Option } = Select;
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  return (
    <Modal
      title="新增渠道"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="渠道名称">
        {form.getFieldDecorator('source', {
          rules: [{ required: true, message: '请输入渠道名称' }],
        })(
          <Select style={{ width: 120 }} placeholder="请选择">
            <Option value="up">sdfz</Option>
            {/* <Option value="xbeauty">想美</Option>
            <Option value="xflower">信花花</Option> */}
          </Select>
        )}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="渠道名称">
        {form.getFieldDecorator('channelName', {
          rules: [{ required: true, message: '请输入渠道名称' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="渠道url">
        {form.getFieldDecorator('channelUrl', {
          rules: [{ required: true, message: '请输入渠道路径' }],
        })(<Input placeholder="请输入" />)}
      </FormItem>
    </Modal>
  );
});

@connect(({ channelStatistics, loading }) => ({
  channelStatistics,
  loading: loading.models.channelStatistics,
}))
@Form.create()
export default class ChannelStatistics extends PureComponent {
  state = {
    modalVisible: false,
    paramList: {
      pageNo: 1,
      startTime: '',
      endTime: '',
      channelName: '',
      source: 'up',
      status: 'ON_LINE',
    },
    status: '',
    startValue: null,
    endValue: null,
    endOpen: false,
  };
  componentDidMount() {
    const { dispatch } = this.props;
    const { paramList } = this.state
    paramList.startTime = moment().startOf('day').subtract(0, 'days').format('YYYY-MM-DD HH:mm:ss');
    paramList.endTime = moment(Date.parse(new Date())).format('YYYY-MM-DD HH:mm:ss');
    this.getChannelData();
    this.getTotalChannelData();
  }

  getChannelData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state
    let postParam = {
      pageNo: paramList.pageNo,
      startTime: paramList.startTime,
      endTime: paramList.endTime,
      channelName: paramList.channelName,
      // source: paramList.source,
      status: paramList.status,
    }
    if (paramList.source) {
      postParam.source = paramList.source
    }
    dispatch({
      type: 'channelStatistics/fetchGetChannelStatistics',
       payload:{
       ...postParam
       }
    });
  };

  getTotalChannelData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state
    let postParam = {
      // source: paramList.source,
      startTime: paramList.startTime,
      endTime: paramList.endTime,
      channelName: paramList.channelName,
      status: paramList.status,
    }
    if (paramList.source) {
      postParam.source = paramList.source
    }
    dispatch({
      type: 'channelStatistics/fetchGetTotalChannelStatistics',
       payload:{
       ...postParam
       }
    });
  };

  getSystemChannelData = () => {
    const { dispatch } = this.props;
    const { paramList } = this.state
    let postParam = {
      // source: paramList.source,
      pageNo: paramList.pageNo,
      status: 'APPLY',
    }
    if (paramList.source) {
      postParam.source = paramList.source
    }
    dispatch({
      type: 'channelStatistics/fetchGetSystemChannelList',
       payload:{
       ...postParam
       }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues, paramList, status } = this.state;
    paramList.pageNo = pagination.current;

    if(status=='APPLY'){
      this.getSystemChannelData();
    }else {
      this.getChannelData();
    }
  };

  handleTab = (key) =>{
    const { paramList } = this.state;
    const { dispatch } = this.props;
    paramList.pageNo = 1;
    paramList.status = key;
    this.setState({
      status: key
    })
    if(key == 'APPLY'){
      this.getSystemChannelData();
    }else {
      this.getChannelData();
      this.getTotalChannelData();
    }
  }

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    const { paramList } = this.state
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      paramList.channelName = fieldsValue.channelName ? fieldsValue.channelName: '';
      paramList.startTime = fieldsValue.startTime? moment(fieldsValue.startTime).format('YYYY-MM-DD HH:mm:ss'):'';
      paramList.endTime = fieldsValue.endTime? moment(fieldsValue.endTime).format('YYYY-MM-DD HH:mm:ss'):'';
      console.log(paramList)
      this.getChannelData();
      this.getTotalChannelData();
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    const { paramList } = this.state
    form.resetFields();
    paramList.startTime = moment().startOf('day').subtract(0, 'days').format('YYYY-MM-DD HH:mm:ss');
    paramList.endTime = moment(Date.parse(new Date())).format('YYYY-MM-DD HH:mm:ss');
    paramList.channelName ='';
    this.getChannelData();
    this.getTotalChannelData();
  };

  handleGoOutLine = (text,record) =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'channelStatistics/fetchDeleteChannel',
      payload:{channelId: record.systemChannelId},
      callback: () =>{
        const { channelStatistics: {outData},} = this.props;
        message.info(outData.message)
        this.getChannelData();
      }
    });
  };

  handleUpLine = val =>{
    const { dispatch } = this.props;
    dispatch({
      type: 'channelStatistics/fetchOnLineChannel',
      payload:{
        ...{channelId: val}
      },
      callback: ()=>{
        this.getSystemChannelData();
      }
    });
  }

  handleNewChannel = () => {
    this.setState({
      modalVisible: true,
    });

  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: false,
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    delete fields.sign
    dispatch({
      type: 'channelStatistics/fetchInsertChannel',
      payload:{
        ...fields
      },
      callback: (res) => {
        this.setState({
          modalVisible: false,
        });
        if (res.code == 200) {
          message.success(res.message)
          this.getSystemChannelData();
          return ;
        } else {
          message.info(res.message)
          return;
        }
      }
    });
  };

  showChannelPage = id =>{
    const {dispatch} = this.props

    window.open('http://www.daydayaup.com/guidePage/channelStatistics.html?channelId='+id)
  };

  //datePicker
  disabledStartDate = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  }
  disabledEndDate = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  }
  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  }
  onStartChange = (value) => {
    this.onChange('startValue', value);
  }
  onEndChange = (value) => {
    this.onChange('endValue', value);
  }
  handleStartOpenChange = (open) => {
    if (!open) {
      this.setState({ endOpen: true });
    }
  }
  handleEndOpenChange = (open) => {
    this.setState({ endOpen: open });
  }


  renderSimpleForm() {
    const { form } = this.props;
    const {status } = this.state
    const { getFieldDecorator } = form;
    const { startValue, endValue, endOpen } = this.state;
    const defaultSelectDate = {
      startDate: moment().startOf('day').subtract(0, 'days'),
      endDate:moment(Date.parse(new Date())),
    }
    return (
      <Card bordered={false}>
        {
          status == 'APPLY' ?
            <Button type="primary"  onClick={() =>{this.handleNewChannel()} }><Icon type="plus" theme="outlined" />新增渠道</Button>
            :
            <Form onSubmit={this.handleSearch} layout="inline">

              <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                <Col md={6} sm={12}>
                  <FormItem label="开始时间">
                    {getFieldDecorator('startTime',{
                      initialValue: defaultSelectDate.startDate
                    })(<DatePicker
                      disabledDate={this.disabledStartDate}
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      value={startValue}
                      placeholder="开始时间"
                      onChange={this.onStartChange}
                      onOpenChange={this.handleStartOpenChange}
                    />)}
                  </FormItem>
                </Col>
                <Col md={6} sm={12}>
                  <FormItem label="结束时间">
                    {getFieldDecorator('endTime',{
                      initialValue:defaultSelectDate.endDate
                    })(<DatePicker
                      disabledDate={this.disabledEndDate}
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      value={endValue}
                      placeholder="结束时间"
                      onChange={this.onEndChange}
                      open={endOpen}
                      onOpenChange={this.handleEndOpenChange}
                    />)}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <FormItem label="渠道名称">
                    {getFieldDecorator('channelName')(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                <span className={styles.submitButtons}>
                  <Button type="primary" htmlType="submit" >
                    查询
                  </Button>
                  <Button  htmlType="submit" style={{marginLeft:12}} onClick={this.handleFormReset}>
                    清除
                  </Button>
                </span>
                </Col>
              </Row>
            </Form>
        }
      </Card>

    );
  }


  render() {
    const { channelStatistics: { channelData,applyData,allChannelData }, loading} = this.props;
    const { status,modalVisible } = this.state;

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    let _arr =[];
    allChannelData? _arr.push(allChannelData): ''
    const tableColumns = [{
        title: '产品类型',
        dataIndex: 'source',
        render: (text, record) => (
          <span>{text == 'up' ? 'sdfz' : text}</span>
          // <span>{text == 'up' ? 'sdfz' : ( text == 'xflower' ? '信花花' : ( text == 'xbeauty' ? '想美' : text ) )}</span>
        )
      },
      {
        title: '渠道名',
        dataIndex: 'channelName',

      },
      {
        title: '上线日期',
        dataIndex: 'createTime',

      },
      {
        title: '流览量',
        dataIndex: 'clickNum',
        render: val => `${val}`
      },
      {
        title: '注册成功',
        dataIndex: 'registerNum',
        render: val => `${val}`
      },
      {
        title: '登录成功',
        dataIndex: 'loginNum',
        render: val => `${val}`
      },
      {
        title: '资料提交',
        dataIndex: 'submitRiskNum',
        render: val => `${val}`
        //
      },
      {
        title: '认证通过',
        dataIndex: 'riskNum',
        render: val => `${val}`
      },
      {
        title: '会员购买',
        dataIndex: 'memberNum',
        render: val => `${val}`
      },
      {
        title: '放款笔数',
        dataIndex: 'paymentNum',
        type: 'longString',
        render: val => `${val}`

      },
      {
        title: '操作',
        dataIndex: 'status',
        render: (text, record) => (
          <Button  disabled={text=='UNDER_LINE'} onClick={() =>{this.handleGoOutLine(text,record)}}>
            {text=='UNDER_LINE' ? '已下线': '下线'}
          </Button>
        )

      },
      {
        title: '生成页面',
        dataIndex: 'systemChannelId',
        render:val => <a href="javascript:;" onClick={()=>{ this.showChannelPage(val)} } >查看</a>

      },
    ]
    const tableAllColumns =[
      {
        title: '流览量',
        dataIndex: 'clickNum',
        render: val => `${val}`
      },
      {
        title: '注册成功',
        dataIndex: 'registerNum',
        render: val => `${val}`
      },
      {
        title: '登录成功',
        dataIndex: 'loginNum',
        render: val => `${val}`
      },
      {
        title: '资料提交',
        dataIndex: 'submitRiskNum',
        render: val => `${val}`
        //
      },
      {
        title: '认证通过',
        dataIndex: 'riskNum',
        render: val => `${val}`
      },
      {
        title: '会员购买',
        dataIndex: 'memberNum',
        render: val => `${val}`
      },
      {
        title: '放款笔数',
        dataIndex: 'paymentNum',
        type: 'longString',
        render: val => `${val}`

      },
    ]
    const tableColumns2 = [
      {
        title: '渠道名',
        dataIndex: 'channelName',

      },
      {
        title: '渠道url',
        dataIndex: 'channelUrl',

      },
      {
        title: '操作',
        dataIndex: 'id',
        render: val => <Button   onClick={()=>{this.handleUpLine(val)} }>上线</Button>

      },

    ]

    const tabs =[
      {
        appName: '已上线',
        appId: 'ON_LINE'
      },
      {
        appName: '已下线 ',
        appId: 'UNDER_LINE'
      },

      {
        appName: '草稿箱',
        appId: 'APPLY'
      },

    ]

    return (
      <PageHeaderLayout title="渠道转化">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>

            <Tabs defaultActiveKey={tabs[0].appId} onChange={this.handleTab} >
              {
                tabs.map((item)=>{
                  return (
                    <TabPane tab={item.appName} key={item.appId} ></TabPane>
                  )
                })
              }
            </Tabs>

            <Table  loading={loading} dataSource={_arr} columns={tableAllColumns} pagination={false} style={{margin:'20px 0'}}/>
          <GeneralTableComponent
           data={status== 'APPLY' ? applyData : channelData}
           columns={status== 'APPLY' ? tableColumns2 : tableColumns}
           loading={loading}
           onChange={this.handleStandardTableChange}
           />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderLayout>
    );
  }
}
